//
//  BiometricPromptView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation
import SwiftUI
import UIKit

struct BiometricPromptView: View {
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) private var dismiss
    

    @State private var biometricSetupCompleted = false
    
    var onLoginComplete: (() -> Void)? = nil
    
    var biometricType: String {
        dataManager.getBiometricType()
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                Color(.systemGroupedBackground)
                    .ignoresSafeArea()
                
                VStack(spacing: 40) {
                    Spacer()
                    
                    // 图标
                    Image(systemName: biometricType == "Face ID" ? "faceid" : "touchid")
                        .font(.system(size: 100))
                        .foregroundColor(.orange)
                    
                    // 标题和描述
                    VStack(spacing: 20) {
                        // 检查用户是否已启用生物识别或刚完成设置
                        if biometricSetupCompleted || (dataManager.currentUser?.biometricLoginEnabled == true) {
                            Text(dataManager.currentLanguage == "zh" ? "\(biometricType)设置成功" : "\(biometricType) Setup Complete")
                                .font(.largeTitle)
                                .fontWeight(.bold)
                                .foregroundColor(.green)
                                .multilineTextAlignment(.center)
                            
                            Text(dataManager.currentLanguage == "zh" ? 
                                 "\(biometricType)登录已成功启用！下次登录时您可以使用\(biometricType)快速安全地访问您的账户。" :
                                 "\(biometricType) login has been successfully enabled! You can now use \(biometricType) to quickly and securely access your account next time.")
                                .font(.body)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.center)
                                .padding(.horizontal, 30)
                                .lineLimit(nil)
                        } else {
                            Text(dataManager.currentLanguage == "zh" ? "设置\(biometricType)登录" : "Set up \(biometricType) Login")
                                .font(.largeTitle)
                                .fontWeight(.bold)
                                .multilineTextAlignment(.center)
                            
                            Text(dataManager.currentLanguage == "zh" ? 
                                 "为了您的便利和安全，我们建议启用\(biometricType)登录。这样您下次就可以快速安全地访问您的账户，无需输入验证码。" :
                                 "For your convenience and security, we recommend enabling \(biometricType) login. This way you can quickly and securely access your account next time without entering a verification code.")
                                .font(.body)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.center)
                                .padding(.horizontal, 30)
                                .lineLimit(nil)
                        }
                    }
                    
                    // 功能特点
                    VStack(spacing: 20) {
                        PromptFeatureRow(
                            icon: "bolt.fill", 
                            title: dataManager.currentLanguage == "zh" ? "快速登录" : "Quick Login", 
                            description: dataManager.currentLanguage == "zh" ? "一秒完成身份验证" : "Complete authentication in one second"
                        )
                        PromptFeatureRow(
                            icon: "lock.shield.fill", 
                            title: dataManager.currentLanguage == "zh" ? "安全可靠" : "Secure & Reliable", 
                            description: dataManager.currentLanguage == "zh" ? "生物特征本地存储，更安全" : "Biometric data stored locally, more secure"
                        )
                        PromptFeatureRow(
                            icon: "person.fill.checkmark", 
                            title: dataManager.currentLanguage == "zh" ? "便捷体验" : "Convenient Experience", 
                            description: dataManager.currentLanguage == "zh" ? "无需记忆密码或验证码" : "No need to remember passwords or codes"
                        )
                    }
                    .padding(.horizontal, 30)
                    
                    Spacer()
                    
                    // 按钮
                    VStack(spacing: 16) {
                        if biometricSetupCompleted || (dataManager.currentUser?.biometricLoginEnabled == true) {
                            // 设置完成后的按钮
                            Button(action: {
                                if AppConfig.enableDebugLogging {
                                    print("[DEBUG] BiometricPromptView: 用户点击完成按钮")
                                }
                                // 无论配置如何，用户在成功状态下点击完成都应该能关闭界面
                                dismiss()
                                onLoginComplete?()
                            }) {
                                HStack {
                                    Image(systemName: "checkmark.circle.fill")
                                        .font(.title2)
                                    
                                    Text(dataManager.currentLanguage == "zh" ? "完成" : "Done")
                                        .fontWeight(.semibold)
                                }
                                .foregroundColor(.white)
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 16)
                                .background(
                                    LinearGradient(
                                        colors: [Color.green, Color.green.opacity(0.8)],
                                        startPoint: .leading,
                                        endPoint: .trailing
                                    )
                                )
                                .cornerRadius(12)
                                .shadow(color: Color.green.opacity(0.3), radius: 8, x: 0, y: 4)
                            }
                        } else {
                            // 设置前的按钮
                            Button(action: {
                                enableBiometricDirectly()
                            }) {
                                HStack {
                                    Image(systemName: biometricType == "Face ID" ? "faceid" : "touchid")
                                        .font(.title2)
                                    
                                    Text(dataManager.currentLanguage == "zh" ? "立即启用\(biometricType)" : "Enable \(biometricType) Now")
                                        .fontWeight(.semibold)
                                }
                                .foregroundColor(.white)
                                .frame(maxWidth: .infinity)
                                .padding(.vertical, 16)
                                .background(
                                    LinearGradient(
                                        colors: [Color.orange, Color.orange.opacity(0.8)],
                                        startPoint: .leading,
                                        endPoint: .trailing
                                    )
                                )
                                .cornerRadius(12)
                                .shadow(color: Color.orange.opacity(0.3), radius: 8, x: 0, y: 4)
                            }
                            
                            Button(dataManager.currentLanguage == "zh" ? "稍后再说" : "Maybe Later") {
                                if AppConfig.enableDebugLogging {
                                    print("[DEBUG] BiometricPromptView: 用户点击稍后再说按钮")
                                }
                                // 无论配置如何，用户点击"稍后再说"都应该能够关闭页面
                                dismiss()
                                onLoginComplete?()
                            }
                            .foregroundColor(.secondary)
                            .font(.body)
                            .padding(.vertical, 12)
                        }
                    }
                    .padding(.horizontal, 30)
                    .padding(.bottom, 40)
                }
            }
            .navigationTitle("")
            .navigationBarHidden(true)
        }
    }
    
    private func enableBiometricDirectly() {
        if AppConfig.enableDebugLogging {
            print("[DEBUG] BiometricPromptView: 直接启用生物识别")
        }
        
        // 首先检查生物识别是否可用
        guard dataManager.isBiometricAvailable() else {
            if AppConfig.enableDebugLogging {
                print("[DEBUG] BiometricPromptView: 生物识别功能不可用")
            }
            return
        }
        
        // 直接调用生物识别验证
        dataManager.authenticateWithBiometrics { success, error in
            DispatchQueue.main.async {
                if AppConfig.enableDebugLogging {
                    print("[DEBUG] BiometricPromptView: 生物识别验证结果 - 成功: \(success), 错误: \(error ?? "无")")
                }
                
                if success {
                    self.dataManager.enableBiometricLogin()
                    
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] BiometricPromptView: 生物识别登录已启用，直接关闭界面")
                    }
                    
                    // 验证成功后直接关闭界面
                    self.dismiss()
                    self.onLoginComplete?()
                } else {
                    // 处理验证失败的情况
                    if AppConfig.enableDebugLogging {
                        print("[DEBUG] BiometricPromptView: 生物识别验证失败")
                    }
                }
            }
        }
    }
}

struct PromptFeatureRow: View {
    let icon: String
    let title: String
    let description: String
    
    var body: some View {
        HStack(spacing: 16) {
            Image(systemName: icon)
                .font(.title2)
                .foregroundColor(.orange)
                .frame(width: 28, height: 28)
            
            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.headline)
                    .foregroundColor(.primary)
                
                Text(description)
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                    .lineLimit(2)
            }
            
            Spacer()
        }
        .padding(.vertical, 8)
    }
}

#Preview {
    BiometricPromptView()
        .environmentObject(DataManager.shared)
}